package com.example.wyh.intelcheckbash;

import android.Manifest;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.wyh.intelcheckbash.bluetoothchat.BluetoothChatFragment;
import com.example.wyh.intelcheckbash.common.SysExitUtil;
import com.example.wyh.intelcheckbash.task.DownloadTaskActivity;
import com.example.wyh.intelcheckbash.task.TaskCheckActivity;

import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;

import static com.example.wyh.intelcheckbash.R.id.alertTitle;
import static com.example.wyh.intelcheckbash.R.id.password;
import static com.example.wyh.intelcheckbash.R.id.username;


/**
 * Created by WYH on 17/9/19.
 */

public class LoginActivity extends AppCompatActivity {
    private String mDeviceToken;
    BluetoothChatFragment mFragment = MainActivity.getInstance();

    String getMac() {
        String macSerial = null;
        String str = "";
        try {
            Process pp = Runtime.getRuntime().exec("cat /sys/class/net/wlan0/address");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);

            for (; null != str;) {
                str = input.readLine();
                if (str != null) {
                    macSerial = str.trim();
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (macSerial == null)
        {
            showAlert("网络未连接，请先连接WIFI");
        }
        return macSerial;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_activity);
        SysExitUtil.activityList.add(LoginActivity.this);

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(LoginActivity.this, new String[]{Manifest.permission.READ_PHONE_STATE}, 8000);
        }
        else
        {
            TelephonyManager TelephonyMgr = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
            mDeviceToken = TelephonyMgr.getDeviceId();
        }

        final String deviceMac = getMac();
        Button loginBtn = (Button) findViewById(R.id.login);
        final EditText userNameText = (EditText)findViewById(username);
        final EditText passwordText = (EditText)findViewById(password);

        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String getDeviceMac = deviceMac;
                if(deviceMac == null)
                {
                    getDeviceMac = getMac();
                }
                String userName = userNameText.getText().toString();
                String password = passwordText.getText().toString();
                String path = "http://www.chasingeda.com:7777/appsoft7/appservlet/?requesttype=login&username="+"sysadmin"+"&password="
                        + "111111" + "&devicetoken=手机的imei&registrationID=极光推送的registrationID&isjpush=1&plat=android";
                login(LoginActivity.this,userName,password,mDeviceToken,getDeviceMac);
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,int[] grantResults) {
        if (requestCode == 8000 && grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            TelephonyManager TelephonyMgr = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
            mDeviceToken = TelephonyMgr.getDeviceId();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if(keyCode == KeyEvent.KEYCODE_BACK){

            try {
                String bluetoothAddress = LocalStorage.getString(LoginActivity.this,"blueToothAddress");
                if (mFragment.mIsConnectedBlueTooth == true && bluetoothAddress.length() != 0)
                {
                    mFragment.connectDeviceWithAddress(bluetoothAddress);
                }
            }catch (Exception e)
            {

            }
            try {
                mFragment.onDestroy();
            }catch (Exception e)
            {
                Log.e("mFragment is null",e.getMessage());
            }
//            try {
//                if (mFragment.mIsConnectedBlueTooth == true)
//                {
//                    try {
//                        mFragment.onDestroy();
//                    }catch (Exception e)
//                    {
//                        Log.e("mFragment.onDestroy()",e.getMessage());
//                    }
//                }
//            }catch (Exception e)
//            {
//                Log.e("mFragment is null",e.getMessage());
//            }
            int siz=SysExitUtil.activityList.size();
            for(int i=0;i<siz;i++){
                if(SysExitUtil.activityList.get(i)!=null){
                    ((Activity) SysExitUtil.activityList.get(i)).finish();
                }
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    public void connectTimedOut(final String message)
    {
        Handler mainHander = new Handler(Looper.getMainLooper());
        mainHander.post(new Runnable() {
            @Override
            public void run() {
                showAlert(message);
            }
        });
    }
    public void jumpToMain(JSONObject jsonObject,String result)
    {
        Log.e("TAG","=====================服务器返回的信息：：" + result);
        boolean isLoginsuccess = false;
        try {
            final String msg = jsonObject.getString("msg");
            if (jsonObject.getString("yhxtm").length() > 0)
            {
                isLoginsuccess = true;
                LocalStorage.saveObject(LoginActivity.this,"User",jsonObject);
                finish();
//                startActivity(new Intent(LoginActivity.this,MainActivity.class));
                return;
            }

            Handler mainHander = new Handler(Looper.getMainLooper());
            mainHander.post(new Runnable() {
                @Override
                public void run() {
                    showAlert(msg);
                }
            });
        }catch (Exception e)
        {
            Log.e("TAG","=================：：" + e);
        }

    }

    public void showAlert(String msg)
    {
        LayoutInflater layoutInflater = LayoutInflater.from(LoginActivity.this);
        final View layout = layoutInflater.inflate(R.layout.promot_alert,
                null);

        final AlertDialog alertDialog = new AlertDialog.Builder(LoginActivity.this).setTitle("").setView(layout)
                .setPositiveButton("",  new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .setNegativeButton("", null).show();

        TextView alert_title = (TextView)layout.findViewById(R.id.promot_alert_title);
        alert_title.setText(msg);
        Button confirm = (Button)layout.findViewById(R.id.promot_confirm);
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });
    }

    public  void updateUser(){

    }

    public void login(Context context,String userName, String password,String deviceToken,String deviceMac) {
        HttpUtil.requestNetForGetLogin(context,userName,password,deviceToken,deviceMac);
    }
}






